package org.apache.cordova.geolocation;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;

import static org.apache.cordova.device.Device.TAG;

/**
 * Created by 席国鹏 on 2020/5/20.
 */
public class LocationService extends Service {
    public static final int ACTION_SETUP = 1;
    public static final int ACTION_PAUSE = 2;
    public static final int ACTION_RESUME = 3;
    public static final int ACTION_STOP = 4;


    public static final int PASS_SINGLE = 1;
    public static final int PASS_ARRAY = 2;

    HybirdLocation hybirdLocation;

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }
    boolean isLocation=false;
    int startId = 0;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand "+startId);
        if(!isLocation){
            if (Build.VERSION.SDK_INT >= 26) {
                setForeground();
            }
            initLocation();
            hybirdLocation.start();
            isLocation = true;
        }
        return startId;
    }

    private String nid = "1026";

    @TargetApi(26)
    private void setForeground() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(nid, "定位", NotificationManager.IMPORTANCE_HIGH);
        manager.createNotificationChannel(channel);
        int tmpImgs =  getResources().getIdentifier("ic_launcher","mipmap",getPackageName());
        Notification notification = new Notification.Builder(this, nid)
                .setContentTitle("正在定位")
                .setContentText("事件采集定位")
                .setSmallIcon(tmpImgs)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), tmpImgs))
                .build();

        startForeground(1, notification);
    }



    @Override
    public IBinder onBind(Intent intent) {
        return new Messenger(mHandler).getBinder();
    }

    Messenger appMessager;//application 使用
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (what == ACTION_SETUP) {
                appMessager = msg.replyTo;
            } else if (what == ACTION_PAUSE) {
                startStore();
            } else if (what == ACTION_RESUME) {
                stopStore();
            } else if(what==ACTION_STOP){
               stopLocation();
            }
        }
    };

    boolean isstore = false;

    private void stopLocation(){
        initLocation();
        hybirdLocation.stop();
        stopForeground(true);
        stopSelf();
        this.isLocation = false;
    }
    private void startStore() {
        isstore = true;
        this.storeLocation.clear();
    }

    private void stopStore(){
        isstore = false;
        Message message = new Message();
        message.what = PASS_ARRAY;
        Object[] objects = storeLocation.toArray();
        message.obj = objects;
        try {
            appMessager.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingPermission")
    private void initLocation() {
     if(hybirdLocation==null){
         hybirdLocation = new HybirdLocation(new HybirdLocation.HBListener() {
             @Override
             public void location(Location location, String type) {
                 if (isstore){
                     storeLocation.add(location);
                 }else{
                     Message message = new Message();
                     message.what = PASS_SINGLE;
                     message.obj = location;
                     try {
                         appMessager.send(message);
                     } catch (RemoteException e) {
                         e.printStackTrace();
                     }
                 }
             }
         },this);
     }
    }

    ArrayList<Location> storeLocation = new ArrayList<Location>();


}
